<?php
/**
 * 库存管理控制器
 * 
 */
class StockController extends App_Zend_Controller_Action_Admin
{	
	/**该方法主要进行的是权限判断*/
	public function init() 
	{
		$user = App_User::getCurrentUser();
		if($user){
			if(!in_array('1', json_decode($user->permission))){
				exit('You have no priviage');
			}
		}else{
			$this->_redirect('/user/login');
		}
		parent::init();		
	}
	
	/**库存列表*/
	public function indexAction()
	{
		/**建立库存表Stock和库存尺码值表StockValue模型*/
        $stock = App_Model::factory('Stock');
        $stockvalue = App_Model::factory('StockValue');
        
        /**取出搜索表单或者分页链接提交过来的数据*/
        $title = $this->getRequest()->getParam('title','');//$this->getRequest()是当前的请求对象，包括模块控制器动作等
        $sku = $this->getRequest()->getParam('sku','');//getParam('sku','')的第二个参数为当没有sku的数据时的默认值
        $page = $this->getRequest()->getParam('page',1);//分页
        $hasen = $this->getRequest()->getParam('has_en','');
        
        /**根据条件获取Stock模型集合，然后转换成数组*/
        $limit = 20;//每页显示数
        $stockList='';
        $stockList  = $stock->listAll($title,$hasen,$sku,$page,$limit)->toArray();
        //$stockListall = $stock->getAllStock();
        if(!empty($stockList)){
        	$skuid=array();
        	/**组合$stockList对象数组里每个对象的sku的值为数组，然后通过该数组获取$stockvalueList即具体库存值，最后再由此分配一一分配回$stockList对象数组*/
        	foreach($stockList as $v){
        		$skuid[]=trim($v['sku']);
        	}
        	$stockvalueList = $stockvalue->getBySku($skuid);
        	foreach($stockList as $k=>$v){
        		foreach($stockvalueList as $key=>$value){
        			if(trim($value['sku'])==trim($v['sku'])){
        				$stockList[$k]['stock'][] = $value;
        			}
        		}
        	}
        	//如果根据产品名称搜索库存,则获取相应搜索结果集的统计数据即比如：总计:S:36,M:32,L:14,XL:35,均码:4
        	if(!empty($title)){
        		$stocklistall = $stock->getByTitle($title)->toArray();
        		foreach ($stocklistall as $stv){
        			$stvalue = $stockvalue->getBySku(trim($stv['sku']))->toArray();
        			foreach ($stvalue as $vv){
        			    $stockvalueListall[] = $vv;
        			}
        		}
        		$total = array();
        		foreach($stockvalueListall as $value){
        			$total[$value['size']] +=  $value['t_value'];
        		}
        		$totalStockStr='总计：';
        		foreach($total as $k=>$v){
        			$totalStockStr.=$k."：".$v."；&nbsp;&nbsp;";
        		}
        		$totalStockStr= trim($totalStockStr,",");
        		$this->view->totalStockStr=$totalStockStr;
        	}
        }
        
        /**将相应的值分配到视图调用*/
        $this->view->stockList = $stockList;
        $this->view->sku=$sku;
        $this->view->has_en=$hasen;
        $this->view->title=$title;
        
        /**生成分页对象*/
		$num = $stock->getTotalNum($sku,$title,$hasen);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num)); 
        $paginator->setItemCountPerPage($limit); // 每页10条 
        $paginator->setCurrentPageNumber($page); 
        $this->view->paginator = $paginator ; //将paginator传到view层
	}
	
	/**新增库存*/
	public function addAction()
	{
		/**建立库存的分类属性StockAttr模型，获取brand和player值*/
		$stockAttr = App_Model::factory('StockAttr');
		$brandlist = $stockAttr->getAttrname('brand');
		$playerlist = $stockAttr->getAttrname('player');
		
		/**将值分配到视图调用*/
		$this->view->brand = $brandlist;
		$this->view->player = $playerlist;
		
        if($this->getRequest()->isPost()) {
        	/**取出表单提交过来的数据*/
            $title = $this->getRequest()->getParam('productname', '');
            $entitle = $this->getRequest()->getParam('productenname', '');
            $sku = $this->getRequest()->getParam('sku', '');
            $brand = $this->getRequest()->getParam('brand', '') == ''? 0:$this->getRequest()->getParam('brand', '');
            $player = $this->getRequest()->getParam('player', '') == ''? 0:$this->getRequest()->getParam('player', '');
            $pattern_size = $this->getRequest()->getParam('pattern_size', '');
            $pattern_size_stock = $this->getRequest()->getParam('pattern_size_stock', '');
			$warning_value = $this->getRequest()->getParam('warning_value', '');
            $is_forlong = $this->getRequest()->getParam('is_forlong', '');

            /**建立库存表Stock、库存值表StockValue和库存属性值模型*/
			$stock = App_Model::factory('Stock');//库存表
			$stockvalue = App_Model::factory('StockValue');//库存值表
			$stockAttrSku = App_Model::factory('StockAttrSku');
			$stockDeladdLog = App_Model::factory('StockDeladdLog');

			$msg = array();
			if (empty($title)) {
				$msg[] = '产品名称不能为空';
			} 
			if (empty($entitle)) {
				$msg[] = '英文标题不能为空';
			} 
			
			if(empty($sku)) {
				$msg[] = 'sku不能为空';
			} else {
				if ($stock->existSku($sku)) {
					$msg[] = 'sku已经存在';
				}
			}
			if(empty($pattern_size[0])){
				$msg[] = '产品型号不能为空';
			}
			
			$tmp = array_unique(array_values($pattern_size));
			if (count($tmp) != count($pattern_size)) {
				$msg[] = '产品尺码有重复';
			}
			
			if (!empty($msg)) {
				/**以下部分的内容主要是为了方便管理员当发生验证性错误时不用重新输入信息*/
				$this->view->msg = $msg;
				$this->view->title = $title;
				$this->view->entitle = $entitle;
				$this->view->sku = $sku;
				$this->view->pattern_size = $pattern_size;
				$this->view->warning_value = $warning_value;
				$this->view->pattern_size_stock = $pattern_size_stock;
				//$this->view->is_forlong = $is_forlong;
				return ;
			}
			
			$db = App_Db::localDb();
			$db->beginTransaction();
			try {
				$stockrow = array('title'=>$title, 'en_title'=>$entitle, 'sku'=>trim($sku), 'is_forlong'=>$is_forlong, 'add_time'=>date('Y-m-d H:i:s', time()),'update_time'=>date('Y-m-d H:i:s', time()));
				$stock->add($stockrow);//新增库存
				$row=array('sku'=>trim($sku),'brand'=>$brand,'player'=>$player);
				$stockAttrSku->add($row);//新增库存属性
				$row2 = array('sku'=>trim($sku),'title'=>$title,'add_time'=>date('Y-m-d H:i:s', time()),'add_user'=>$_SESSION['User']['user']['user_name'],'isadd'=>'1');
				$stockDeladdLog->add($row2);

				foreach($pattern_size as $k=>$v){
					if(trim($v)!=''){
						$row = array('sku'=>trim($sku),'size'=>trim($v),'value'=>intval($pattern_size_stock[$k]),'t_value'=>intval($pattern_size_stock[$k]),'warning_value'=>intval($warning_value[$k]));
						$stockvalue->add($row);//新增库存值
					}
				}	
				$db->commit();
				$msg[] = '添加成功';
			} catch (Exception $e) {
				$db->rollback();
				$msg[] = '添加失败';
			}
			
			$this->view->msg = $msg;
        }
	}
	
	/**修改库存*/
	public function updateAction()
	{
		/**建立修改库存时涉及的模型*/
		$stock = App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');
		$stockAttrSku = App_Model::factory('StockAttrSku');
		$stockAttr = App_Model::factory('StockAttr');
	    $StockNumlog = App_Model::factory('StockNumlog');//库存量变化日志
		
		if($this->getRequest()->isPost()) {
			/**取出表单提交过来的数据*/
			$row=array();
			$stock_id = $this->getRequest()->getParam('id', '');
			$row['title'] = $this->getRequest()->getParam('productname', '');
			$row['en_title'] = $this->getRequest()->getParam('productenname', '');
			$pattern_size = $this->getRequest()->getParam('pattern_size', '');
			$pattern_size_stock = $this->getRequest()->getParam('pattern_size_stock', '');
			$warning_value = $this->getRequest()->getParam('warning_value', '');
			$row['is_forlong'] = $this->getRequest()->getParam('is_forlong', '');

			/**获取要修改的模型*/
			$stockRow = $stock->getOne($stock_id);
			$msg = array();
			
			if (!$stockRow) {
				$msg[] = 'error';
				exit('error');
			}
			
			if (empty($row['title'])) {
				$msg[] = '产品名称不能为空';
			} 
			if(empty($pattern_size[0])){
				$msg[] = '产品型号不能为空';
			}			
			$tmp = array_unique(array_values($pattern_size));
			if (count($tmp) != count($pattern_size)) {
				$msg[] = '产品尺码有重复';
			}
			
			if ($msg) {
				$this->view->msg = $msg;

				$stocklist = $stock->getOne($stock_id);			
				if(!empty($stocklist)){
					$stockvaluelist = $stockvalue->getBySku($stocklist['sku']);
				}
				$this->view->stockvaluelist = $stockvaluelist;
				$this->view->stocklist = $stocklist;
				return;
			}
			
			$db = App_Db::localDb();
			$db->beginTransaction();
			try {							
				$stock->update($row,$stock_id);	//修改库存stock
				$oldstockvalue = $stockvalue->getBySku($stockRow['sku'])->toArray();
				$oldSize = array();
				foreach ($oldstockvalue as $os){
					$oldSize[] = $os['size'];
					//判断是否尺码被删除了
					if(!in_array($os['size'], $pattern_size)){
						$stockvalue->deleteById($os['id']);
					}
				}
				
				foreach($pattern_size as $k=>$v){
					//判断尺码是否是新增的
					if(!in_array($v, $oldSize)){
						$row = array('sku'=>trim($stockRow['sku']),'size'=>trim($v),'value'=>intval($pattern_size_stock[$k]),'t_value'=>intval($pattern_size_stock[$k]),'warning_value'=>intval($warning_value[$k]));
						$stockvalue->add($row);//新增库存值
					}
					
					foreach ($oldstockvalue as $ov){
						if($ov['size'] == $v){
							$value = intval($ov['value'])+intval($pattern_size_stock[$k])-intval($ov['t_value']);//实际库存加减多少，理论库存也加减多少
							$row = array('sku'=>trim($ov['sku']),'size'=>trim($v),'value'=>$value,'t_value'=>intval($pattern_size_stock[$k]),'warning_value'=>intval($warning_value[$k]));
							$stockvalue->update($row,$ov['id']);
							$info = array();
							if(abs($pattern_size_stock[$k]-intval($ov['t_value']))>0){
								$info[]=array('size'=>$v,'value'=>$pattern_size_stock[$k]-$ov['t_value']);
								$numlog = array('sku'=>trim($ov['sku']),'title'=>$stockRow['title'],'info'=>json_encode($info),'addtime'=>date('Y-m-d H:i:s', time()),'adduser'=>$_SESSION['User']['user']['user_name'],'ischeck'=>1);
								$StockNumlog->add($numlog);
							}
						}
					}
				}
				$rowAttr = array('player'=>$player,'brand'=>$brand);
				$stockAttrSku->update($rowAttr,$stockRow['sku']);
				
				$db->commit();
				$msg[] = '修改成功';
			} catch (Exception $e) {
				$db->rollback();
				$msg[] = '修改失败';
			}	
			$this->view->msg = $msg;
		}
		
		$stock_id = $this->getRequest()->getParam('id', 0);
		$stock_id = intval($stock_id);
		if($stock_id!=0){
			/**获取要修改的库存的模型*/
			$stocklist = $stock->getOne($stock_id);		
			if(!empty($stocklist)){
				$stockvaluelist = $stockvalue->getBySku($stocklist['sku']);
				//获取分类
				$brandlist = $stockAttr->getAttrname('brand');
				$playerlist = $stockAttr->getAttrname('player');
				$AttridList = $stockAttrSku->getBySku($stocklist['sku']);
			}
		}
		
		/**将值分配到视图调用*/
		$this->view->AttridList = $AttridList;
		$this->view->brand = $brandlist;
		$this->view->player = $playerlist;
		$this->view->stockvaluelist = $stockvaluelist;
		$this->view->stocklist = $stocklist;
	}
	
	/**修改库存理论值和实际值*/
	public function updatestockvalueAction()
	{
		$stockvalue = App_Model::factory('StockValue');
		$stock = App_Model::factory('Stock');
		
		if($this->getRequest()->isPost()) {
			$row=array();
			$id = $this->getRequest()->getParam('id', '');
			$value = $this->getRequest()->getParam('value', '0');
			$t_value = $this->getRequest()->getParam('t_value', '0');

			$db = App_Db::localDb();
			$db->beginTransaction();
			try {
				$stockvalue->update(array('value'=>$value,'t_value'=>$t_value),$id);
				$db->commit();
				$msg[] = '修改成功';
			} catch (Exception $e) {
				$db->rollback();
				$msg[] = '修改失败';
			}	
			
		}
		
		$id = $this->getRequest()->getParam('id', 0);
		$id = intval($id);
		if($id!=0){
			/**获取要修改的库存的模型*/
			$list = $stockvalue->getOne($id);
		}
		$this->view->msg = $msg;
		$this->view->list = $list[0];
	}
	
	/**增减库存数量*/
	public function addnumAction()
	{
		if($this->getRequest()->isPost()) {
			$row=array();
			$stock_id = $this->getRequest()->getParam('id', '');
			$pattern_size = $this->getRequest()->getParam('pattern_size', '');
			$pattern_size_stock = $this->getRequest()->getParam('pattern_size_stock', '');

			$stock = App_Model::factory('Stock');
			$stockvalue = App_Model::factory('StockValue');
			$StockNumlog = App_Model::factory('StockNumlog');//库存量变化日志
			
			$stockRow = $stock->getOne($stock_id);
				
			$db = App_Db::localDb();
			$db->beginTransaction();
			$info=array();
			try {
				foreach($pattern_size as $k=>$v){
					if(intval($pattern_size_stock[$k])!=0){
						$stockvalue->addtnum($stockRow['sku'],$v,intval($pattern_size_stock[$k]));//增加实际库存
						$stockvalue->addnum($stockRow['sku'],$v,intval($pattern_size_stock[$k]));//增加理论库存
						$info[]=array('size'=>$v,'value'=>intval($pattern_size_stock[$k]));
					}
				}
				$numlog = array('sku'=>$stockRow['sku'],'title'=>$stockRow['title'],'info'=>json_encode($info),'addtime'=>date('Y-m-d H:i:s', time()),'adduser'=>$_SESSION['User']['user']['user_name'],'ischeck'=>1);
				$StockNumlog->add($numlog);
				$db->commit();
				$msg[] = '修改成功';
			} catch (Exception $e) {
				$db->rollback();
				$msg[] = '修改失败';
			}
			$this->view->msg = $msg;
		}
	
		$stock_id = $this->getRequest()->getParam('id', 0);
		$stock_id = intval($stock_id);
		if($stock_id!=0){
			$stock = App_Model::factory('Stock');
			$stockvalue = App_Model::factory('StockValue');
			$stocklist = $stock->getOne($stock_id);
			if(!empty($stocklist)){
				$stockvaluelist = $stockvalue->getBySku($stocklist['sku']);
			}
		}
		$this->view->stockvaluelist = $stockvaluelist;
		$this->view->stocklist = $stocklist;
	}
	
	/**异常库存列表*/
	public function unusualAction()
	{
        $stockvalue = App_Model::factory('StockValue');
        
        $page = $this->getRequest()->getParam('page',1);//分页
        $sku = $this->getRequest()->getParam('sku','');
        $limit = 20;//每页显示数

        if(empty($sku)){
        	$list = $stockvalue->listUnusual($page,$sku,$limit);
        	
        	/**将相应的值分配到视图调用*/
        	$this->view->stockList = $list;
        	$this->view->page=$page;
        	
        	/**生成分页对象*/
        	$num = $stockvalue->getTotalUnusualNum();
        	$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        	$paginator->setItemCountPerPage($limit);
        	$paginator->setCurrentPageNumber($page);
        	$this->view->paginator = $paginator ; //将paginator传到view层
        }else{
        	$list = $stockvalue->listUnusual($page,$sku,$limit);
        	$this->view->stockList = $list;
        	$this->view->sku = $sku;
        }
	}
	
	/**特殊问题出入库管理*/
	public function specialmanageAction()
	{
		$stock_id = $this->getRequest()->getParam('id', 0);
		$stock_id = intval($stock_id);
		
		/**是否有提交了数据*/
		if($this->getRequest()->isPost()) {
			$row=array();
			$flag = 1;
			$orderid = $this->getRequest()->getParam('orderid', '0');//订单号
			$dutyuser = $this->getRequest()->getParam('dutyuser', '');//责任人
			$remark = $this->getRequest()->getParam('remark', '');//事件原因
			$pattern_size = $this->getRequest()->getParam('pattern_size', '');//尺码
			$pattern_size_change = $this->getRequest()->getParam('pattern_size_change', '');//变化数量
		
			$stock = App_Model::factory('Stock');//库存表
			$stockvalue = App_Model::factory('StockValue');//库存尺码数量值表
			$StockNumlog = App_Model::factory('StockNumlog');//库存量变化日志表，但用来存放特殊库管日志
		
			$stockRow = $stock->getOne($stock_id);

			if(1 == 1){
				$db = App_Db::localDb();
				$db->beginTransaction();//开启事务
				$info=array();
				try {
					foreach($pattern_size as $k=>$v){
						if(intval($pattern_size_change[$k]) > 0){
							$stockvalue->addtnum($stockRow['sku'],$v,intval($pattern_size_change[$k]));//改变实际库存
							$stockvalue->addnum($stockRow['sku'],$v,intval($pattern_size_change[$k]));//改变理论库存
							$info[]=array('size'=>$v,'value'=>'+'.abs(intval($pattern_size_change[$k])));
						}else if(intval($pattern_size_change[$k]) < 0){
							$stockvalue->minustnum($stockRow['sku'],$v,abs(intval($pattern_size_change[$k])));
							$stockvalue->minusnum($stockRow['sku'],$v,abs(intval($pattern_size_change[$k])));
							$info[]=array('size'=>$v,'value'=>intval($pattern_size_change[$k]));
						} else {
							$stockvalue->addtnum($stockRow['sku'],$v,intval($pattern_size_change[$k]));
							$stockvalue->addnum($stockRow['sku'],$v,intval($pattern_size_change[$k]));
							$info[]=array('size'=>$v,'value'=>'+'.intval($pattern_size_change[$k]));
						}
					}
					$numlog = array(
							'sku'=>$stockRow['sku'],
							'title'=>$stockRow['title'],
							'info'=>json_encode($info),
							'addtime'=>date('Y-m-d H:i:s', time()),
							'adduser'=>$_SESSION['User']['user']['user_name'],
							'orderid'=>$orderid,
							'isspecial'=>1,
							'dutyuser'=>$dutyuser,
							'remark'=>$remark,
							'ischeck'=>1);
					$StockNumlog->add($numlog);
					$db->commit();
					$msg[] = '数据提交成功';
				} catch (Exception $e) {
					$db->rollback();
					$msg[] = '数据提交失败';
				}
			}
			
			$this->view->msg = $msg;
		}

		if($stock_id!=0){
			$stock = App_Model::factory('Stock');
			$stockvalue = App_Model::factory('StockValue');
			$stocklist = $stock->getOne($stock_id);
			if(!empty($stocklist)){
				$stockvaluelist = $stockvalue->getBySku($stocklist['sku']);
			}
		}
		$this->view->stockvaluelist = $stockvaluelist;
		$this->view->stocklist = $stocklist;
	}
	
	/**库存删除*/
	public function deleteAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$stock_id = $this->getRequest()->getParam('id', 0);
		$stock_id = intval($stock_id);
		if($stock_id!=0){
			$stock = App_Model::factory('Stock');
			$stockvalue = App_Model::factory('StockValue');
			$stockAttrSku = App_Model::factory('StockAttrSku');
			$stockDeladdLog = App_Model::factory('StockDeladdLog');
			
			$db = App_Db::localDb();
			$db->beginTransaction();
			try {						
				$row = $stock->getOne($stock_id);
				$res = $stock->delete($stock_id);
				if(!empty($row['sku'])){
					$result = $stockvalue->delete($row['sku']);
					$res = $result&&$res;
				}
				$stockAttrSku->delete($row['sku']);
				$row2 = array('sku'=>$row['sku'],'title'=>$row['title'],'add_time'=>date('Y-m-d H:i:s', time()),'add_user'=>$_SESSION['User']['user']['user_name'],'isadd'=>'0');
				$stockDeladdLog->add($row2);
				$db->commit();
				echo 1;
			} catch (Exception $e) {
				$db->rollback();
				echo 0;
			}	
		}
	}
	
	/**当前库存导出*/
	public function exportcurstockAction()
	{
		$stock = App_Model::factory('Stock');
		//获取当前仓库存在的库存的产品，搜索1、永不下架为是的；2、永不下架为否的且理论库存大于0
		$list = $stock->currentstock();
	
		$fp = fopen(_WEB_DIR_ . '/curstock.csv', 'w');
		$title = array('SKU', 'Title','is_forlong','Size','Value');
		fputcsv($fp, $title);
		foreach ($list as $v) {
			$v['size'] = trim($v['size']) == '均码'?'Average':$v['size'];
			if($v['is_forlong']){
				fputcsv($fp, array($v['sku'], $v['en_title'],'Yes',$v['size'],$v['value']));
			}else{
				fputcsv($fp, array($v['sku'], $v['en_title'],'No',$v['size'],$v['value']));
			}
		}
		fclose($fp);
	}
	
	/**低库存列表，显示缺库存的产品*/
	public function exportlowstockAction()
	{
        $stock = App_Model::factory('Stock');
        $lowStockList = $stock->getLowStock();//获取低库存的产品
        $stockListSku=array();
        foreach($lowStockList as $k=>$v){
        	$stockListSku[$v['sku']]['title']=$v['title'];
        	$stockListSku[$v['sku']]['sku']=$v['sku'];
        	$stockListSku[$v['sku']]['is_forlong']=$v['is_forlong']?'是':'否';
        	$stockListSku[$v['sku']]['stock'][$k]['warning_value']=$v['warning_value'];
        	$stockListSku[$v['sku']]['stock'][$k]['value']=$v['value'];
        	$stockListSku[$v['sku']]['stock'][$k]['size']=$v['size']; 	
        }

        $fp = fopen(_WEB_DIR_ . '/lowstock.csv', 'w');
        $title = array('SKU', '产品', '库存状态', '是否永不下架');
        fputcsv($fp, $title);
        foreach ($stockListSku as $v) {
        	$str="";
        	foreach($v['stock'] as $_v){
        		if ($_v['value'] < $_v['warning_value']) {
        			$str.=$_v['size'] . '/' .($_v['value']-$_v['warning_value']);
        		}
        		$str.='   ';
        	}
        	fputcsv($fp, array($v['sku'], $v['title'],$str,$v['is_forlong']));
        }
        fclose($fp);
        $this->view->outStockList = $lowStockList;
        $this->view->stockListSku = $stockListSku;
	}

	/**实际缺货列表*/
	public function exportoutstockAction()
	{
		$stockLog = App_Model::factory('StockLog');//网站订单日志表模型
		$sortlog = App_Model::factory('OrderSortLog');//订单分拣日志表
        $stock = App_Model::factory('Stock');
		$outstocklogs = $stockLog->getStockLog(array('statu'=>1))->toarray();
        $outstockInfo=array();
        //处理可能出现的尺码重复问题
        foreach ($outstocklogs as $lk=>$lv){
        	$linfo = json_decode($lv['info'], true);
        	$vinfo = '';
        	foreach($linfo as $v1){
        		$vnum = 0;
        		foreach ($linfo as $v2){
        			if($v1[0] == $v2[0]){
        				$vnum += $v2[1];
        			}
        		}
        		$flag = true;
        		foreach ($vinfo as $v3){
        			if($v1[0] == $v3[0]){
        				$flag = false;
        			}
        		}
        		if($flag){
        			$vinfo[] = array($v1[0],"$vnum");
        		}
        	}
        	$outstocklogs[$lk]['info']=json_encode($vinfo);
        }
        //给$outstocklogs增加标题信息、修改info信息
        foreach ($outstocklogs as &$v){
	    	$sortloglist = $sortlog->getSortLog(array('order_id'=>$v['order_id'],'site'=>$v['site'],'sku'=>$v['sku']))->toarray();
	    	$stockitem = $stock->getBySku($v['sku'])->toarray();
	    	$info = json_decode($v['info']);//该订单该SKU下的尺码与数量数组
	    	//统计分拣了的该订单该SKU下各尺码的数量
	    	foreach ($info as &$sv){
	    		foreach ($sortloglist as $vv){
	    			 if($sv[0] == $vv['size']){
	    			 	$sv[1] -= 1;
	    			 }
	    		}
	    	}
	    	$v['info'] = json_encode($info);
	    	$v['title'] = $stockitem[0]['title'];
        }

        //重组$outstocklogs数组，其元素的sku值相同的那些元素要相邻排列
        $temp = array();//重置成新的数组
        $flag = array();//记录那些相同sku的键值
        for($i = 0;$i<count($outstocklogs);$i++){
        	if(in_array($i, $flag)){
        		
        	}else{
        		$k = array();
        		for($j=$i+1;$j<count($outstocklogs);$j++){
        			if(trim($outstocklogs[$i]['sku']) == trim($outstocklogs[$j]['sku'])){
        				$flag[] = $j;
        				$k[] = $j;
        			}
        		}
        		$temp[] = $outstocklogs[$i];
        		if(!empty($k)){
        			foreach ($k as $kv){
        				$temp[] = $outstocklogs[$kv];
        			}
        		}
        	}
        }
        
        $this->view->outstocklogs = $temp;
        
        $fp = fopen(_WEB_DIR_ . '/outstock.csv', 'w');
        $title = array('SKU', '产品', '缺货信息');
        fputcsv($fp, $title);
        foreach ($outstocklogs as $ov) {
        	$info = json_decode($ov['info']);
        	$str="";
        	foreach ( $info as $_v ) {
        		if($_v[1]>0){
        			$str.=$_v[0] . '/' . $_v[1];
        			$str.='   ';
        		}
        	}
        	fputcsv($fp, array($ov['sku'], $ov['title'],$str));
        }
        fclose($fp);
	}

	/**低库存批量打印*/
	public function printlowAction()
	{
		$this->getHelper('layout')->setLayout('nolayout');//设置显示打印信息页面的布局
		$printList = array();
		$stock = App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');
		$cpModel = App_Model::factory('StockCategoryPrice');
	
		$printArr = $this->getRequest()->getParam('isprint', 0);//获取需要批量打印的库存的sku数组
		if(!empty($printArr)){
			foreach($printArr as $sku){
				/**根据sku码的前面字母标志取出该类库存产品对应的信息，包括成本价及市场定价*/
				preg_match('/([A-Z]+)/',$sku,$matches);
				if(!empty($matches[1])){
					$row = $cpModel->getByShortsku($matches[1])->toArray();
				}
				$stockitem = $stock->getBySku($sku)->toArray();
				$skuid = str_pad($stockitem[0]['stock_id'],5,"0",STR_PAD_LEFT);//将stock的id转换成5位字符串
				$tmpValue=$stockvalue->getBySku($sku)->toArray();
				foreach ($tmpValue as $k=>$v){
					if($v['value']<$v['warning_value']){
						$printList[] = array('title'=>$stockitem[0]['title'], 'codename'=>$skuid.$v['id'],'size'=>$v['size'],'num'=>$v['warning_value']-$v['value'],'price'=>$row[0]['b_price']);
					}
				}
			}
		}else{
			$this->view->msg='操作失败，请先请勾选要打印的项！';
		}
		$this->view->lowstocklogs=$printList;
	}
	
	/**实际缺库存批量打印*/
	public function printoutAction()
	{
		$this->getHelper('layout')->setLayout('nolayout');//设置显示打印信息页面的布局
		$printList = array();
		$stock = App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');  
		$cpModel = App_Model::factory('StockCategoryPrice');
		
		$printArr = $this->getRequest()->getParam('isprint', 0);//获取需要批量打印的库存的sku数组
		$size = $this->getRequest()->getParam('size');
		$num = $this->getRequest()->getParam('num');
		if(!empty($printArr)){
			foreach($printArr as $sku){
				/**根据sku码的前面字母标志取出该类库存产品对应的信息，包括成本价及市场定价*/
				preg_match('/([A-Z]+)/',$sku,$matches);
				if(!empty($matches[1])){
					$row = $cpModel->getByShortsku($matches[1])->toArray();
				}
				$stockitem = $stock->getBySku($sku)->toArray();
				$skuid = str_pad($stockitem[0]['stock_id'],5,"0",STR_PAD_LEFT);//将stock的id转换成5位字符串
				foreach ($size[$sku] as $k=>$sv){
					$svitem = $stockvalue->getStockValue(array('sku'=>$sku,'size'=>$sv))->toArray();
					$printList[] = array('title'=>$stockitem[0]['title'],'codename'=>$skuid.$svitem[0]['id'],'size'=>$sv,'num'=>$num[$sku][$k],'price'=>$row[0]['b_price']);
				}
			}
		}else{
			$this->view->msg='操作失败，请先请勾选要打印的项！';
		}
		
        $this->view->outstocklogs = $printList;
	}
	
	/**根据报货日志批量打印对应条码*/
	public function printbaohuoAction()
	{
		$this->getHelper('layout')->setLayout('nolayout');//设置显示打印信息页面的布局
		$sizenum = $this->getRequest()->getParam('sizenum');
		$memo = $this->getRequest()->getParam('memo');
		$excel = $this->getRequest()->getParam('excel');
		$stock = App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');  
		$cpModel = App_Model::factory('StockCategoryPrice');
		if(trim($excel) == 'excel'){
			$this->getHelper('viewRenderer')->setNoRender();
			$this->getHelper('layout')->disableLayout();
			if(!empty($sizenum)){
				$fp = fopen(_WEB_DIR_ . '/baohuo.csv', 'w');
				fputcsv($fp, array('进仓确认表'));
				fputcsv($fp, array('填表日期：'.date('Y-m-d', time())));
				$title = array('名称', '型号', '尺码规格', '单价', '金额', '备注');
				fputcsv($fp, $title);
				
				foreach ($sizenum as $sku=>$sz){
					$info = '';
					$stockitem = $stock->getBySku($sku)->toArray();
					
					foreach ($sz as $k=>$sv){
						foreach ($sv as $size=>$num ){
							$info = $info.$size . '/' .$num . ';';
						}
					}
					fputcsv($fp, array($stockitem[0]['title'], '', $info, '', '', $memo[$sku]));
				}
				fclose($fp);
				echo "<script>location.href='/baohuo.csv';</script>";
			}else{
				exit('Please select the item you want to excel!');
			}
		}else{
			if(!empty($sizenum)){
				foreach ($sizenum as $sku=>$sz){
					/**根据sku码的前面字母标志取出该类库存产品对应的信息，包括成本价及市场定价*/
					preg_match('/([A-Z]+)/',$sku,$matches);
					if(!empty($matches[1])){
						$row = $cpModel->getByShortsku($matches[1])->toArray();
					}
					$stockitem = $stock->getBySku($sku)->toArray();
					$skuid = str_pad($stockitem[0]['stock_id'],5,"0",STR_PAD_LEFT);//将stock的id转换成5位字符串
					foreach ($sz as $k=>$sv){
						foreach ($sv as $size=>$num ){
							$svitem = $stockvalue->getStockValue(array('sku'=>$sku,'size'=>$size))->toArray();
							$printList[] = array('title'=>$stockitem[0]['title'],'codename'=>$skuid.$svitem[0]['id'],'size'=>$size,'num'=>$num,'price'=>$row[0]['b_price']);
						}
					}
				}
			}else{
				$this->view->msg='操作失败，请先勾选要打印的项！';
			}
			$this->view->baohuologs = $printList;
		}
	}

	/**显示需要生成的条形码的具体信息：在库存列表中显示的打印操作就是交给该动作去处理*/
	public function printAction()
	{
		$this->getHelper('layout')->setLayout('nolayout');//设置显示打印信息页面的布局
	
		$cpModel = App_Model::factory('StockCategoryPrice');
		$sku = $this->getRequest()->getParam('sku','');
	
		/**根据sku码的前面字母标志取出该类库存产品对应的信息，包括成本价及市场定价*/
		preg_match('/([A-Z]+)/',$sku,$matches);
		if(!empty($matches[1])){
			$row = $cpModel->getByShortsku($matches[1])->toArray();
		}
		$stock = App_Model::factory('Stock');
		$stockvalue = App_Model::factory('StockValue');
		if(!empty($sku)){
			$stockvalueList = $stockvalue->getBySku($sku)->toArray();
			$stockList = $stock->getBySku($sku)->toArray();
		}
		$this->view->stockvalueList=$stockvalueList;
		$this->view->stockList=$stockList;
		$this->view->price = $row[0]['b_price'];
	}
	
	/**生成条形码，把条形码输出到页面中*/
	public function createwordAction()
	{
		$codename = $this->getRequest()->getParam('codename', '');//$codename条形码=已经转换成5位长度的sku码id+本身就是5位长度的尺码id+4位长度的日期
		$num = $this->getRequest()->getParam('num', '');
		$price = $this->getRequest()->getParam('price', '');
		$size = $this->getRequest()->getParam('size', '');
		$stock = App_Model::factory('Stock');
		$requestArray=array();
		foreach ($codename as $k=>$v){
			$i=$num[$k];
			while($i>0){
				$skuid = intval(substr($v,0,5));
				$sku = $stock->getOne($skuid)->sku;
				$requestArray[]=array(
					'sku'=>$sku,
					'v'=>$v,
					'size'=>$size[$k],
					'price'=>$price[$k],
				);
				$i--;
			}
		}
		
		if (empty($requestArray) || empty($num)){
			$this->view->msg='fail';
		}else{
		    $this->getHelper('viewRenderer')->setNoRender();//用来启用或禁用自动解析，默认设置为true，在当前控制器内，postDispatch()不会调用render()方法。这个设定在preDispatch()每次执行时会被重置。getNoRender()返回当前的设定值。 
		    $this->getHelper('layout')->disableLayout();//禁用layout 
		    $str = '';
		    foreach($requestArray as $k=>$value){
		    	$str = $str . "<iframe scrolling='no' height='100%' width='100%' frameborder='0' style='display:block;' src='".$this->getHelper('url')->url(array('controller'=>'stock','action'=>'barcode','sku'=>$value['sku'],'v'=>$value['v'],'size'=>$value['size'],'price'=>$value['price']))."'></iframe>";
		    }
			echo $str;exit();//将$str的html内容输出到页面
		}
	}

	/**条形码图像页面*/
	public function barcodeAction()
	{
		$this->getHelper('layout')->setLayout('barlayout');//设置显示打印信息页面的布局
		
		$sku = $this->getRequest()->getParam('sku');
		$v = $this->getRequest()->getParam('v');
		$price = $this->getRequest()->getParam('price', '');
		$size = $this->getRequest()->getParam('size', '');
		$stock = App_Model::factory('Stock');
		
		if(empty($sku) || empty($v)){
			$this->view->msg='error';
		}else{
			$a = $stock->getBySku($sku)->toArray();//根据sku码调用stock模型里的getEnSubject函数获取相应网站上的商品信息集（含标题subject字段）
			
			$this->view->v=$v;
			$this->view->price=$price;
			$this->view->size=$size;
			$this->view->url='http://stock.gogoalshop.com/stock/image?filetype=PNG&dpi=72&scale=2&rotation=0&font_family=0&font_size=3&text='.$v.'&thickness=30&start=C&code=BCGcode128';;
			$this->view->text=$sku.'S'.substr($v, 5);
			$this->view->title=$a[0]['en_title'];
		}
	}
	
	/**生成条形码图像*/
	public function imageAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		define('IN_CB', true);
		include_once('App/barcodegen/html/include/function.php');
		$requiredKeys = array(
				'code', //code=BCGcode128
				'filetype', //filetype=PNG
				'dpi', //dpi=72
				'scale', //scale=2
				'rotation', //rotation=0
				'font_family', //font_family=Arial.ttf
				'font_size', //font_size=16
				'text',//text=条形码编号
				//'thickness',//thickness=60
				//'start',//start=C
		);
	
		foreach ($requiredKeys as $key) {
			if (!isset($_GET[$key])) {
				showError();
			}
		}
		if (!preg_match('/^[A-Za-z0-9]+$/', $_GET['code'])) {
			showError();
		}
	
		$code = $_GET['code'];
		include_once('App/barcodegen/html/config' . DIRECTORY_SEPARATOR . $code . '.php');//该文件也就是BCGgs1128.php
		$class_dir = 'App/barcodegen' . DIRECTORY_SEPARATOR . 'class';
		require_once($class_dir . DIRECTORY_SEPARATOR . 'BCGColor.php');
		require_once($class_dir . DIRECTORY_SEPARATOR . 'BCGBarcode.php');
		require_once($class_dir . DIRECTORY_SEPARATOR . 'BCGDrawing.php');
		require_once($class_dir . DIRECTORY_SEPARATOR . 'BCGFontFile.php');
	
		if (!include_once($class_dir . DIRECTORY_SEPARATOR . $classFile)) {//$classFile在文件BCGgs1128.php里定义为BCGgs1128
			showError();
		}
		
		include_once('App/barcodegen/html/config' . DIRECTORY_SEPARATOR . $baseClassFile);//$baseClassFile在BCGgs1128.php里定义为BCGBarcode1D.php
	
		$filetypes = array('PNG' => BCGDrawing::IMG_FORMAT_PNG, 'JPEG' => BCGDrawing::IMG_FORMAT_JPEG, 'GIF' => BCGDrawing::IMG_FORMAT_GIF);
		$drawException = null;
		//下面就是根据$_GET['text']来生成条形码图像的
		try {
			$color_black = new BCGColor(0, 0, 0);
			$color_white = new BCGColor(255, 255, 255);
			$code_generated = new $className();
			if (function_exists('baseCustomSetup')) {
				baseCustomSetup($code_generated, $_GET);
			}
			if (function_exists('customSetup')) {
				customSetup($code_generated, $_GET);
			}
			$code_generated->setScale(max(1, min(4, $_GET['scale'])));
			$code_generated->setBackgroundColor($color_white);
			$code_generated->setForegroundColor($color_black);
				
			if ($_GET['text'] !== '') {
				$text = convertText($_GET['text']);
				$code_generated->parse($text);
			}
		} catch(Exception $exception) {
			$drawException = $exception;
		}
	
		$drawing = new BCGDrawing('', $color_white);
		if($drawException) {
			$drawing->drawException($drawException);
		} else {
			$drawing->setBarcode($code_generated);
			$drawing->setRotationAngle($_GET['rotation']);
			$drawing->setDPI($_GET['dpi'] === 'NULL' ? null : max(72, min(300, intval($_GET['dpi']))));
			$drawing->draw();
		}
		switch ($_GET['filetype']) {
			case 'PNG':
				header('Content-Type: image/png');
				break;
			case 'JPEG':
				header('Content-Type: image/jpeg');
				break;
			case 'GIF':
				header('Content-Type: image/gif');
				break;
		}
		$drawing->finish($filetypes[$_GET['filetype']]);
	}

	/**将条形码的内容输出到word文档上，并进行下载*/
	public function wordAction($data,$filename)
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		if(empty($data)) return '';
		$dt="";
		$dt.='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">';
		$dt.='<xml><w:WordDocument><w:View>Print</w:View></xml>';
		$dt.=$data;
		$dt.='</html>';
		$filename=date('YmdHis').$filename;
		$fp=fopen("./word/".$filename,'a+b');
		fwrite($fp,$dt);
		fclose($fp);
		$path="./word/".$filename;
		$this->downloadActon($path);//下载word文档
	}
	
	/**下载文档*/
	private function downloadActon($sFilePath)
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		if(file_exists($sFilePath)){
			$aFilePath=explode("/",$sFilePath);
			$sFileName=$aFilePath[count($aFilePath)-1];
			$nFileSize=filesize ($sFilePath);
			header ("Content-Disposition: attachment; filename=" .basename($sFileName) );
			header ("Content-Length: " . $nFileSize);
			header ("Content-type: application/octet-stream");
			//mb_convert_encoding(readfile($sFilePath),"utf-8","GB2312");
			readfile($sFilePath);
		}
	}
	
	/**出库扫描时候根据条码ID减库存*/
	public function minustockAction()
	{
		/**禁用视图和布局以便可以echo输出内容*/
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$msg = 'fail';
		if($this->getRequest()->isPost()) {
			/**获取提交上来的表单内容*/
			$isArr = $this->getRequest()->getParam('isadd');
			$barcode = $this->getRequest()->getParam('barcode');
			$sku = $this->getRequest()->getParam('sku');
			$title = $this->getRequest()->getParam('title');
			$size = $this->getRequest()->getParam('size');
			$price = $this->getRequest()->getParam('price');
			$bprice = $this->getRequest()->getParam('b_price');
			$addtime = $this->getRequest()->getParam('addtime');
			
			$stockValue = App_Model::factory('StockValue');//新建包含库存尺码数量值表的模型
			
			$db = App_Db::localDb();
			$db->beginTransaction();
			if(!empty($isArr)){
				try {
					foreach($isArr as $k){
						$infos = json_encode(array(array('size'=>$size[$k],'value'=>1)));
						$stockValue->minustnum($sku[$k],$size[$k],1);
					}
					$db->commit();
					$msg = 'success';
				} catch (Exception $e) {
					$db->rollback();
					$msg = 'fail';
				}
			}
		}
		
		echo "<script>location.href='/log/scanout/msg/".$msg."';</script>";
	}
	
	/**进库扫描的时候根据条形码ID加入库存*/
	public function addstockAction()
	{
		/**禁用视图和布局以便可以echo输出内容*/
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$msg = 'fail';
		if($this->getRequest()->isPost()) {
			/**获取提交上来的表单内容*/
			$isArr = $this->getRequest()->getParam('isadd');
			$barcode = $this->getRequest()->getParam('barcode');
			$sku = $this->getRequest()->getParam('sku');
			$title = $this->getRequest()->getParam('title');
			$size = $this->getRequest()->getParam('size');
			$price = $this->getRequest()->getParam('price');
			$bprice = $this->getRequest()->getParam('b_price');
			$addtime = $this->getRequest()->getParam('addtime');
			
			$StockNumlog = App_Model::factory('StockNumlog');//库存量变化日志
			$stockValue = App_Model::factory('StockValue');//新建包含库存尺码数量值表的模型
			
			$db = App_Db::localDb();
			$db->beginTransaction();
			if(!empty($isArr)){
				try {
					foreach($isArr as $k){
						//$info = '[{"size":"'.$size[$k].'","value":1}]';//存进数据库的就是这种格式
						$infos = json_encode(array(array('size'=>$size[$k],'value'=>1)));
						$stockValue->addtnum($sku[$k],$size[$k],1);
						$stockValue->addnum($sku[$k],$size[$k],1);
						$numlog = array('sku'=>$sku[$k],'title'=>$title[$k],'info'=>$infos,'addtime'=>$addtime[$k],'adduser'=>$_SESSION['User']['user']['user_name'],'ischeck'=>1);
						$StockNumlog->add($numlog);
					}
					$db->commit();
					$msg = 'success';
				} catch (Exception $e) {
					$db->rollback();
					$msg = 'fail';
				}
			}
		}
		
		echo "<script>location.href='/log/scanimport/msg/".$msg."';</script>";
	}
	
	/**出库扫描的时候根据条形码ID进行出库，并生成实际出库日志*/
	public function exportstockAction()
	{
		/**禁用视图和布局以便可以echo输出内容*/
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$msg = 'fail';
		if($this->getRequest()->isPost()) {
			/**获取提交上来的表单内容*/
			$billid = $this->getRequest()->getParam('billid');
			$site = $this->getRequest()->getParam('site');
			$isArr = $this->getRequest()->getParam('isprint');
			$barcode = $this->getRequest()->getParam('barcode');
			$sku = $this->getRequest()->getParam('sku');
			$title = $this->getRequest()->getParam('title');
			$size = $this->getRequest()->getParam('size');
			$price = $this->getRequest()->getParam('price');
			$bprice = $this->getRequest()->getParam('b_price');
			$isgift = $this->getRequest()->getParam('isgift');
			$addtime = $this->getRequest()->getParam('addtime');
			
			$exportlog = App_Model::factory('StockExportlog');//新建存储出库日志表的模型
			$stockValue = App_Model::factory('StockValue');//新建包含库存尺码数量值表的模型
			
			$db = App_Db::localDb();
			$db->beginTransaction();
			if(!empty($isArr)){
				try {
					foreach($isArr as $k){
						//$info = '[{"size":"'.$size[$k].'","value":1}]';//存进数据库的就是这种格式
						$infos = json_encode(array(array('size'=>$size[$k],'value'=>1)));
						$stockValue->minusnum($sku[$k],$size[$k],1);
						$data = array('bill'=>$billid,'sku'=>$sku[$k],'site'=>$site,'info'=>$infos,'isgift'=>$isgift[$k],'add_time'=>strtotime($addtime[$k]),'adduser'=>$_SESSION['User']['user']['user_name']);
						$exportlog->add($data);
					}
					$db->commit();
					$msg = 'success';
				} catch (Exception $e) {
					$db->rollback();
					$msg = 'fail';
				}
			}
		}
		
		echo "<script>location.href='/log/scanexport/msg/".$msg."';</script>";
	}
	
	/**库存增删记录*/
	public function deladdAction()
	{
        $stockDeladd = App_Model::factory('StockDeladdLog');

        $sku = $this->getRequest()->getParam('sku','');
        $page = $this->getRequest()->getParam('page',1);
        $isadd = $this->getRequest()->getParam('isadd','');
        $starttime = $this->getRequest()->getParam('starttime','');
        $endtime = $this->getRequest()->getParam('endtime','');
        
        $pageNum = 10;//每页显示条数
        $deladdList = $stockDeladd->listAll($sku,$isadd,$starttime,$endtime,$page, $pageNum)->toArray();
        
        $this->view->deladdList = $deladdList;
        $this->view->starttime = $starttime;
        $this->view->endtime = $endtime;
        $this->view->sku = $sku;
        $this->view->isadd = $isadd;
        
        $num = $stockDeladd->getTotalNum($sku,$isadd,$starttime,$endtime);
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($num));
        $paginator->setItemCountPerPage($pageNum);
        $paginator->setCurrentPageNumber($page);
        $this->view->paginator = $paginator ;
	}
	
	/**库存盘点，首先是统计盘点传来的数据每种SKU的各个码都有多少个，然后是从数据库获取对应的每种SKU的各个码都有多少个*/
	public function inventoryAction()
	{
		if($this->getRequest()->isPost()) {
            $barcodes = $this->getRequest()->getParam('barcode','');
            $barcodes = json_decode(str_replace('\\r\\n', '',json_encode($barcodes)));
            $len = strlen($barcodes);
            $msg = '';
            $pattern = '/[0-9]+/';
            preg_match($pattern, $barcodes, $matches);//匹配获取数字部分
            if($len % 14 == 0 && $matches[0] == $barcodes && !empty($barcodes)){
            	$k = $len / 14;
            	$sizeid = array();
            	for($i=0;$i<$k;$i++){
            		$barcode = substr($barcodes, 14*$i, 14);
            		$ssid = substr($barcode,5,-4);
            		$sizeid[] = $ssid;
            	}
            }else{
            	$msg = 'error';
            	$this->view->msg = $msg;
            }
            if(empty($msg)){
            	$sizeid = array_count_values($sizeid);
            	$stockvalue = App_Model::factory('StockValue');
            	$exitlist = $stockvalue->inventoryExit($sizeid);//盘点等于上传过来的尺码id集的
            	
            	$this->view->exitlist = $exitlist;
            	$this->view->sizeid = $sizeid;
            }
		}
	}
	
	/**更新库存盘点*/
	public function updateinventoryAction()
	{
		$times = trim($this->getRequest()->getParam('times',''));
        $stockinventory = App_Model::factory('StockInventory');
        $stockvalue = App_Model::factory('StockValue');
        $flag = $this->getRequest()->getParam('flag',false);
        
        if(!empty($times)){
        	$this->view->times = $times;
        	$exitlist = $stockinventory->getStockInventory(array('times' => $times))->toArray();
        	$sizeid = array();
        	foreach($exitlist as $v){
        		$sizeid[] = $v['size_value_id'];
        	}
        	$sizeid = array_count_values($sizeid);
        	$exitlist = $stockvalue->inventoryExit($sizeid);//盘点等于上传过来的尺码id集的
        	$this->view->exitlist = $exitlist;
        	
        	if($flag){
        		$db = App_Db::localDb();
        		$db->beginTransaction();
        		try {
        			foreach($sizeid as $id => $num){
        				$stockvalue->update(array('t_value'=>$num,'value'=>$num),$id);
        			}
        			$db->commit();
        			$msg = 'success';
        		} catch (Exception $e) {
        			$db->rollback();
        			$msg = 'fail';
        		}
        		
        		$misslist = $stockvalue->inventoryMiss($sizeid);//盘点不等于上传过来的尺码id集的
        		
        		$fp = fopen(_WEB_DIR_ . '/missingstock.csv', 'w');
        		$title = array('SKU', '产品名称','尺码','盘点值','记录值','永不下架');
        		fputcsv($fp, $title);
        		foreach ($misslist as $v) {
        			if($v['t_value'] != 0 || $v['value'] != 0){
        				$v['is_forlong'] = $v['is_forlong']?'是':'否';
        				fputcsv($fp, array($v['sku'], $v['title'], $v['size'], 0, $v['t_value'], $v['is_forlong']));
        				//$stockvalue->update(array('t_value'=>'0','value'=>'0'),$v['id']);//更新那些盘点中的扫描没有，而系统记录系有哪些库存的值为0
        			}
        		}
        		fclose($fp);
        		$this->view->msg = $msg;
        	}else{
        		$exitlist = $stockvalue->inventoryExit($sizeid);//盘点等于上传过来的尺码id集的
            	$this->view->sizeid = $sizeid;
        		$this->view->exitlist = $exitlist;
        	}
        }
	}
	
	/**提交库存盘点*/
	public function submitinventoryAction()
	{
		$sku = $this->getRequest()->getParam('sku','');
		$title = $this->getRequest()->getParam('title','');
		$size = $this->getRequest()->getParam('size','');
		$sizevalueid = $this->getRequest()->getParam('sizevalueid','');
		$inventoryvalue = $this->getRequest()->getParam('inventoryvalue','');
		$times = trim($this->getRequest()->getParam('times',''));
		
		if(empty($inventoryvalue) || empty($sizevalueid) || empty($times)){
			$msg = 'fail';
		}else{
			$db = App_Db::localDb();
			$db->beginTransaction();
            $stockvalue = App_Model::factory('StockValue');
            $stockinventory = App_Model::factory('StockInventory');
			try {
				foreach($sizevalueid as $i => $id){
					for($k=0; $k<intval($inventoryvalue[$i]);$k++){
						$row = array('sku' => $sku[$i], 'size' => $size[$i], 'title' => $title[$i], 'size_value_id' => $sizevalueid[$i], 'times' => $times, 'inventory_value' => '1');
						$stockinventory->add($row);
					}
				}
				$db->commit();
				$msg = 'success';
			} catch (Exception $e) {
				$db->rollback();
				$msg = 'fail';
			}
		}
		$this->view->msg = $msg;
	}
	
	/**一键更新所有SKU标题加上英文*/
	public function updatentitleAction() 
	{
        $stock = App_Model::factory('Stock');
        $allStock = $stock->listEmptyEntitle()->toArray();
        $stockid = '00';
        foreach ($allStock as $v){
        	$etitle=json_decode($stock->getEnSubject($v['sku']),1);
        	if(!empty($etitle[0]['subject'])){
			    $row['en_title'] = $etitle[0]['subject'];
				$stock->update($row,$v['stock_id']);	//更新库存标题
        	}
        	$stockid = $v['stock_id'];
        }
        exit($stockid);
	}
	
	/**一键更新所有stockvalue值*/
	public function updateallstockvalueAction()
	{
        $stockvalue = App_Model::factory('StockValue');
		$allstockvalue = $stockvalue->getStockValue()->toArray();
		foreach ($allstockvalue as $v){
			$row = array('sku'=>$v['sku'],'size'=>$v['size'],'value'=>$v['value'],'t_value'=>$v['value'],'warning_value'=>$v['warning_value']);
			$stockvalue->update($row,$v['id']);
		}
		exit('finish');
	}
	
	/**一键同步所有库存的理论值和实际值，对于那些理论库存大于实际库存的情况*/
	public function syncstockvalueAction()
	{
        $stockvalue = App_Model::factory('StockValue');
        $list = $stockvalue->getUnusualValue();
        foreach ($list as $v){
        	if($v['is_forlong']){//永不下架的
        	    if($v['t_value'] < 0){
        		    //$stockvalue->update(array('t_value'=> 0, 'value'=> 1),$v['id']);
        	    }else{
        	    	dump($v,false);
        		    //$stockvalue->update($row,$v['id']);
        	    }
        	}
        }
        exit('end');
	}
	
	/**一键更新所有stockvalue的警报值为0*/
	public function updatewarningvalueAction()
	{
		$stockvalue = App_Model::factory('StockValue');
		$allstockvalue = $stockvalue->getStockValue()->toArray();
		
		$db = App_Db::localDb();
		$db->beginTransaction();
		try {
			foreach($allstockvalue as $v){
				if($v['warning_value']){
					$row = array('warning_value'=>'0');
					$stockvalue->update($row,$v['id']);
				}
			}
			$db->commit();
			$msg = 'success';
		} catch (Exception $e) {
			$db->rollback();
			$msg = 'fail';
		}
		
		exit('finish');
	}
}